﻿using Digitalmes.Domain;
using Digitalmes.Domain.Mes;
using Digitalmes.Scada.Models;
using Digitalmes.Sugar;

namespace Digitalmes.Scada.Services.Impl;

internal sealed class TakePartInService : ITakePartInService, ITransientDependency
{
    private readonly SugarRepository<ProdTransSn> _transSnRepo;
    //private readonly SugarRepository<ReworkDoc> _reworkDocRepo;
    private readonly SugarRepository<QcReworkRecord> _reworkRecordRepo;

    public TakePartInService(SugarRepository<ProdTransSn> transSnRepo,
        SugarRepository<QcReworkRecord> reworkRecordRepo)
    {
        _transSnRepo = transSnRepo;
        //_reworkDocRepo = reworkDocRepo;
        _reworkRecordRepo = reworkRecordRepo;
    }

    public async Task<HandleResult> TakePartInAsync(TakePartInInput input)
    {
        // 前提是检测产品是否是返修件且完成返修
        var transSn = await _transSnRepo.GetFirstAsync(s => s.Sn == input.SN && s.CurLineCode == input.LineCode);
        if (transSn == null)
        {
            return HandleResult.Error(ErrCode.E1402);
        }

        // 返工后会转为 OK 状态
        if (transSn.Status != Domain.Enums.SnStatusEnum.OK)
        {
            return HandleResult.Error(ErrCode.E1405);
        }

        // 仅仅从返工记录中检查
        // 检查 SN 当前状态且是否在返修工位有记录
        // 思考：通过对比返工记录的 Version 与最近一次 Archive 记录的 Version，确认是否已返工。
        var reworkRecord = await _reworkRecordRepo.GetLastAsync(s => s.Sn == input.SN && s.NgProcId == transSn.CurProcId);
        if (reworkRecord == null)
        {
            return HandleResult.Error(ErrCode.E1405);
        }

        // 根据放工单来检查是否已返工
        //if (transSn.ReworkFlag is not Domain.Enums.ReworkFlagEnum.DoneAndWaitToRelaunch)
        //{
        //    return HandleResult.Error(ErrCode.E1403);
        //}

        //var reworkDoc = await _reworkDocRepo.GetFirstAsync(s => s.Doc == transSn.ReworkDoc);
        //if (reworkDoc == null)
        //{
        //    return HandleResult.Error(ErrCode.E1404);
        //}

        //if(reworkDoc.Status is not Domain.Enums.ReworkStatusEnum.Completed)
        //{
        //    return HandleResult.Error(ErrCode.E1405);
        //}

        return HandleResult.Ok(new()
        {
            { "MES_Callback_Station", transSn.CurProcCode }, // 工序编号与工位编号一致
        });
    }
}
